import React, { useEffect, useRef, useState } from 'react'
import './chart.less'
import { Chart } from '@antv/g2'

const Charts = () => {
	const chartRef = useRef()
	const data = [
		{ name: '杭州银行', num: 8 },
		{ name: '南京银行', num: 10 },
		{ name: '江西邮储', num: 7 },
		{ name: '小叮咚科技', num: 6 },
		{ name: '南宁科技', num: 5 },
		{ name: '南宁科技1', num: 5 },
		{ name: '南宁科技2', num: 6 },
		{ name: '南宁科技3', num: 7 },
		{ name: '南宁科技4', num: 8 },
		{ name: '南宁科技5', num: 9 },
		{ name: '南宁科技6', num: 10 },
		{ name: '南宁科技7', num: 2 },
		{ name: '南宁科技8', num: 8 },
	]

	const [chart, setChart] = useState(null)
	const [maxHeight, setMaxHeight] = useState(null)

	useEffect(() => {
		if (data && !chart) {
			const maxH = data.length * 50
			setMaxHeight(maxH)
			const chart = new Chart({
				container: 'c10',
				width: 500,
				height: maxH,
				nice: true,
			})
			setChart(chart)
		}
	}, [data])

	useEffect(() => {
		chart && renderChart()
	}, [chart])

	const renderChart = () => {
		const margin = 1 / 6
		const averageNum = 6
		const contentColor = '#F59a23'
		const content = `评价及格线: ${averageNum}分`
		chart.clear()
		chart.data(data)

		chart.scale('num', {
			range: [0, 1 - margin / 2],
			min: 0,
			max: 10,
			tickCount: 7,
			nice: true,
		})

		chart.axis('num', {
			label: {
				formatter: () => '',
			},
		})
		chart.coordinate().transpose()

		chart.tooltip({
			showTitle: false,
			showMarkers: false,
		})

		chart.interaction('active-region')

		chart
			.interval()
			.size(24)
			.label('num', {
				offset: -10,
			})
			.tooltip('name*num', (name, num) => {
				return {
					showTitle: false,
					name: name,
					value: `${num}`,
				}
			})
			.position('name*num')

		chart.annotation().line({
			top: true,
			start: [-0.5, averageNum],
			end: [data.length + 0.5, averageNum],
			style: {
				// 辅助线样式
				stroke: contentColor,
				lineWidth: 1,
				lineDash: [3, 3],
			},
			text: {
				position: 'start',
				style: {
					// 辅助线文本样式
					fill: contentColor,
					fontSize: 12,
					fontWeight: 500,
				},
				content: content,
				offsetY: -5,
				autoRotate: false,
			},
		})

		chart.render()
	}

	return (
		<div className={'chart10'}>
			<div id="c10" ref={chartRef} style={{ height: maxHeight }} />
		</div>
	)
}

export default Charts
